package com.pansoft.kline.fragment;


import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.recycleviewhelper.MultiItemTypeAdapter;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.formatter.IValueFormatter;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.google.gson.Gson;
import com.pansoft.kline.activity.BourseActivity;
import com.pansoft.kline.adapter.BourseRecycleViewAdapter;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.helper.BtcKanConfigAndRateHelper;
import com.pansoft.kline.model.BourseDataBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.MarketMenuBean;
import com.pansoft.kline.util.BtcKanNumberFormatUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.constant.MarketConstant;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 行情-交易所界面
 *
 * @author yqs
 */
public class BourseFragment extends BaseFragment {

    private static final String TAG = "BourseFragment";

    private View rootView;
    private SmartRefreshLayout refreshLayout;
    private BarChart barChart;
    private RecyclerView recycleview;
    private TextView tvTopTitle;


    private List<BarEntry> barEntryList;
    private MarketMenuBean.DataBean.CategoryBean.ListBean menuBean;
    private BourseRecycleViewAdapter bourseRecycleViewAdapter;
    private List<BourseDataBean.DataBean.ExchangeVolumesBean> mDatas;

    private int page = 1;
    //当前货币code 如CNY USD
    private String currencyCode;

    public static BourseFragment newInstance(MarketMenuBean.DataBean.CategoryBean.ListBean bean) {
        BourseFragment fragment = new BourseFragment();
        Bundle args = new Bundle();
        args.putSerializable("bean", bean);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.assets_fragment_bourse, container, false);
        currencyCode = CurrencyAndBourseManager.getCurrencyUnitCode();
        initView();
        initAdaper();
        super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        JFCommonRequestManager.getInstance(getContext()).cannelOkHttpRequest(TAG);
    }

    private void initView() {
        refreshLayout = (SmartRefreshLayout) rootView.findViewById(R.id.rfl_btckan);
        barChart = (BarChart) rootView.findViewById(R.id.barChart);
        tvTopTitle = (TextView) rootView.findViewById(R.id.tv_top_title);

        recycleview = (RecyclerView) rootView.findViewById(R.id.recycleview);
        recycleview.setLayoutManager(new LinearLayoutManager(getActivity()));
        recycleview.setNestedScrollingEnabled(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page += 1;
                requestData(page);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                requestData(page);
            }
        });
        tvTopTitle.setText(getString(R.string.open_planet_bourse_text1, CurrencyAndBourseManager.getNowCurrencySymbol()));
        initBarChart();
    }

    private void initAdaper() {
        mDatas = new ArrayList<>();
        bourseRecycleViewAdapter = new BourseRecycleViewAdapter(getActivity(), R.layout.assets_item_market_bourse, mDatas);
        recycleview.setAdapter(bourseRecycleViewAdapter);
        refreshLayout.autoRefresh();
        bourseRecycleViewAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                if (position == 0 || mDatas.size() <= position) {
                    return;
                }
                BourseActivity.start(_mActivity, mDatas.get(position).getSiteName());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 初始化柱形图
     */
    private void initBarChart() {
//        barChart.setExtraTopOffset(-30f);
        barChart.setExtraBottomOffset(5f);
        barChart.setExtraLeftOffset(10f);
        barChart.setExtraRightOffset(10f);
        barChart.setFitBars(true);//使两侧的柱图完全显示
        barChart.animateX(500);//数据显示动画，从左往右依次显示
        barChart.setScaleEnabled(false);
        barChart.setDrawBarShadow(false);
        barChart.setDrawValueAboveBar(true);
        barChart.getDescription().setEnabled(false);
        // scaling can now only be done on x- and y-axis separately
        barChart.setPinchZoom(false);
        barChart.setDrawGridBackground(false);

        //设置x轴
        XAxis xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setGranularity(1f); // only intervals of 1 day
        xAxis.setLabelCount(7);
        //设置轴
        xAxis.setTextColor(Color.LTGRAY);
        xAxis.setTextSize(10f);
        xAxis.setDrawAxisLine(false);


        YAxis leftAxis = barChart.getAxisLeft();
        leftAxis.setLabelCount(8, false);
        leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART);
        leftAxis.setSpaceTop(10f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        //y轴左侧数值
        leftAxis.setDrawLabels(false);
        //不画y轴的线
        leftAxis.setDrawAxisLine(false);
        leftAxis.setDrawGridLines(false);


        barChart.getAxisRight().setEnabled(false);
        barChart.getLegend().setEnabled(false);

    }

    private void requestData(int page) {
        menuBean = (MarketMenuBean.DataBean.CategoryBean.ListBean) getArguments().getSerializable("bean");

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("volume_size", "20");
        hashMap.put("volume_page", String.valueOf(page));


        JFCommonRequestManager.getInstance(getActivity()).requestGetByAsyn(TAG, MarketConstant.MARKET_BOURSE_URL, hashMap, new JFCommonRequestManager.ReqCallBack<String>() {
            @Override
            public void onReqSuccess(String result) {
                try {
                    refreshLayout.finishRefresh(100);
                    refreshLayout.finishLoadMore(100);
                    BourseDataBean bourseDataBean = new Gson().fromJson(result, BourseDataBean.class);
                    if (bourseDataBean.getCode() != 0) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                        return;
                    }
                    List<BourseDataBean.DataBean.ExchangeVolumesBean> exchangeVolumesBeanList = bourseDataBean.getData().getExchange_volumes();

                    List<BourseDataBean.DataBean.FundsBean> fundsBeanList = bourseDataBean.getData().getFunds();
                    initRecycleViewData(exchangeVolumesBeanList);
                    initBarChartData(fundsBeanList);

                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                refreshLayout.finishRefresh(100);
                refreshLayout.finishLoadMore(100);
            }
        });


    }

    private void initRecycleViewData(List<BourseDataBean.DataBean.ExchangeVolumesBean> exchangeVolumesBeanList) {
        if (page == 1) {
            mDatas.clear();
            mDatas.add(new BourseDataBean.DataBean.ExchangeVolumesBean());
            bourseRecycleViewAdapter.notifyDataSetChanged();
        }
        if (exchangeVolumesBeanList != null) {
            //处理数据，更换site 名称以及价值更改为rmb(返回的是美元)
            for (int i = 0; i < exchangeVolumesBeanList.size(); i++) {
                final BourseDataBean.DataBean.ExchangeVolumesBean temp = exchangeVolumesBeanList.get(i);
                final String siteName = temp.getSite();
                temp.setSiteName(siteName);
                ConfigSiteBean siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(siteName);
                if (siteBean != null) {
                    temp.setSite(siteBean.getTitle());
                }
                //
                BtcKanConfigAndRateHelper.getRate(new BtcKanConfigAndRateHelper.RateCallBack() {
                    @Override
                    public void obtainRate(boolean isSuccess, JSONObject rateObject) {

                        try {
                            String rate = rateObject.getJSONObject(siteName).getString(currencyCode);
                            double value = TCMathUtil.mul(temp.getVolume() + "", rate);
                            temp.setVolume(value);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
            }
            mDatas.addAll(exchangeVolumesBeanList);
            bourseRecycleViewAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 初始化上方柱形图数据
     *
     * @param fundsBeanList
     */
    private void initBarChartData(List<BourseDataBean.DataBean.FundsBean> fundsBeanList) {
        if (fundsBeanList == null) {
            return;
        }
        barEntryList = new ArrayList<>();
        List<Integer> colors = new ArrayList<>();
        int green = getResources().getColor(R.color.increasing_color);
        int red = getResources().getColor(R.color.decreasing_color);

        for (int i = 0; i < fundsBeanList.size(); i++) {
            final BourseDataBean.DataBean.FundsBean fundsBean = fundsBeanList.get(i);
            float balance = MarketNumberUtils.calculateIncomeing(fundsBean.getIncomes(), fundsBean.getOutputs());

            //取绝对值
            BarEntry entry = new BarEntry(i, Math.abs(balance));

            entry.setData(fundsBean);
            barEntryList.add(entry);
            if (fundsBean.getNet_flow_type() == 1) {
                //1表示净流入
                colors.add(green);
            } else {
                //-1 表示小于0
                colors.add(red);
            }
        }

        barChart.getXAxis().setValueFormatter(new AxisFormatter(fundsBeanList));
        //设置标签显示的个数
        barChart.getXAxis().setLabelCount(fundsBeanList.size());

        BarDataSet set;

        if (barChart.getData() != null &&
                barChart.getData().getDataSetCount() > 0) {
            set = (BarDataSet) barChart.getData().getDataSetByIndex(0);
            set.setValues(barEntryList);
            barChart.getData().notifyDataChanged();
            barChart.notifyDataSetChanged();
        } else {
            set = new BarDataSet(barEntryList, "表一");
            set.setColors(colors);
            set.setValueTextColors(colors);

            BarData data = new BarData(set);
            data.setValueTextSize(13f);
            data.setValueFormatter(new DataFormatter());
            //柱体宽度 这里设为0.6f那么柱体之间的间距就为0.4f
            data.setBarWidth(0.5f);
            barChart.setData(data);
            barChart.invalidate();
        }
    }

    /**
     * 数据格式转换
     */
    private class DataFormatter implements IValueFormatter {

        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            BourseDataBean.DataBean.FundsBean bean = (BourseDataBean.DataBean.FundsBean) entry.getData();
            String rate = null;
            try {
                rate = BtcKanConfigAndRateHelper.getRate(null).getJSONObject(bean.getSite()).optString(currencyCode, null);
                if (rate == null) {
                    //处理闪退异常
                    rate = "1";
                }

                double income = TCMathUtil.mul(bean.getIncomes() + "", rate);
                double output = TCMathUtil.mul(bean.getOutputs() + "", rate);

                float balance = MarketNumberUtils.calculateIncomeing(income, output);
                return BtcKanNumberFormatUtil.keep2Decimal(balance);
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }


    }

    /**
     * x轴数据格式转换
     */
    private class AxisFormatter implements IAxisValueFormatter {

        private List<BourseDataBean.DataBean.FundsBean> fundsBeanList;

        public AxisFormatter(List<BourseDataBean.DataBean.FundsBean> fundsBeanList) {
            this.fundsBeanList = fundsBeanList;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            String site = fundsBeanList.get(Math.min(Math.max((int) value, 0), fundsBeanList.size() - 1)).getSite();
            ConfigSiteBean siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(site);
            if (siteBean != null) {
                site = siteBean.getTitle();
            }
            return site;
        }
    }
}
